var IN = true;
var NOT_IN = false;
var INDENTS = ['\t', ' '];
function next(in_or_not, str, chars, offset) {
	var retn = -1;
	for(; offset < str.length; i++) {
		var c = str.charAt(offset);
		var result = chars.indexOf(c);
		if((in_or_not && result > -1) || (!in_or_not && result < 0) {
			retn = offset;
			break;
		} 
	}
	return retn;
}
function read_str(str, offset) {
	var i = next(NOT_IN, str, INDENTS, offset);
	if(i == -1) return null; // non-indent character not found
	var start = str.charAt(i);
    if(start === '"' || start == "'") {
		close = [start];
	} else {
		close = INDENTS;
	}
	// find close or to the end of str
	for(end = start + 1; end < str.length; end++) {
		var c = str.charAt(end);
		if(close.indexOf(c) > -1) {
			break;
		}
	}
	return [start, end]
}
function multiple(str, times) {
	var retn = '';
	for(int i = 0; i < times; i++) {
		retn = retn + str;
	}
	return retn;
}
function render(data){
	var lines = data.split('\n');
	var stack = [];
	var indent = null;
	for(var line_no = 0; line_no < lines.length; line_no++){
		var line = lines[line_no];
		if(!line || line.length == 0 || line[0] === '#') continue;
		range = read_str(line, 0);
		if(range == null) continue;
		var curr_indent = str.substr(0, range[0]);
		var indent_level;
		if(indent) { // indent is defined
			// what level of current indent is
			indent_level = parsetInt(curr_indent.length / indent.length);
			if(multiple(indent, indent_level) !== curr_indent){
				alert("Bad indent at line: " + line_no);
				return;
			}
		} else {
			if(curr_indent.length == 0) { // top level
				indent_level = 0;
			} else {
				indent = curr_indent;
				indent_level = 0;
			}
		}
		var key = str.substring(range[0], range[1]);
		var val = str.substring(range[1]);
	}
}

var xmlhttp;
if (window.XMLHttpRequest) {
    //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
    xmlhttp=new XMLHttpRequest();
} else {
    // IE6, IE5 浏览器执行代码
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open('GET', 'data/ships.txt', true);
xmlhttp.send()
xmlhttp.onreadystatechange = function() {
	if(xmlhttp.readyState == 4) {
		if(xmlhttp.status != 200) {
			alert("Server returns " + xmlhttp.status)
		}
		render(xmlhttp.responseText);
	}
}
